[-*Smarty*-]

[-config_load file="default.conf"-]
[-*Load the Language Definitions*-]
[-config_load file="lang.$USER_LANG"-]
[-include file="$TPL_NAME/views/header.html"-]

[-php-]
/*echo "<pre>";
print_r($_SESSION);
echo "</pre>";*/
[-/php-]

[-*Values used in setting timeslot and event heights*-]
[-php-]
/* if you change these be sure to change their matching values in
 * the CSS for the calendar, found in interface/themes/ajax_calendar.css
 */
$timeslotHeightVal=20;
$timeslotHeightUnit="px";

 // this is my proposed setting in the globals config file so we don't
 // need to mess with altering the pn database AND the config file
 //pnModSetVar(__POSTCALENDAR__, 'pcFirstDayOfWeek', $GLOBALS['schedule_dow_start']);

 // build a day-of-week (DOW) list so we may properly build the calendars later in this code
 $DOWlist = array();
 $tmpDOW = pnModGetVar(__POSTCALENDAR__, 'pcFirstDayOfWeek');
 // bound check and auto-correction
 if ($tmpDOW <0 || $tmpDOW >6) { 
    pnModSetVar(__POSTCALENDAR__, 'pcFirstDayOfWeek', '0');
    $tmpDOW = 0;
 }
 while (count($DOWlist) < 7) {
    array_push($DOWlist, $tmpDOW);
    $tmpDOW++;
    if ($tmpDOW > 6) $tmpDOW = 0;
 }

 // A_CATEGORY is an ordered array of associative-array categories.
 // Keys of interest are: id, name, color, desc, event_duration.
 //
 // echo "<!-- A_CATEGORY = "; print_r($this->_tpl_vars['A_CATEGORY']); echo " -->\n"; // debugging
 // echo "<!-- A_EVENTS = "; print_r($this->_tpl_vars['A_EVENTS']); echo " -->\n"; // debugging

 $A_CATEGORY  =& $this->_tpl_vars['A_CATEGORY'];

 // [-if $PRINT_VIEW != 1-]
 // [-*Main Navigation*-]
 // [-include file="$TPL_NAME/views/global/navigation.html"-]
 // [-/if-]

 
 
 $A_EVENTS  =& $this->_tpl_vars['A_EVENTS'];
 $providers =& $this->_tpl_vars['providers'];
 $times     =& $this->_tpl_vars['times'];
 $interval  =  $this->_tpl_vars['interval'];
 $viewtype  =  $this->_tpl_vars['VIEW_TYPE'];
 $PREV_WEEK_URL = $this->_tpl_vars['PREV_WEEK_URL'];
 $NEXT_WEEK_URL = $this->_tpl_vars['NEXT_WEEK_URL'];
 $PREV_DAY_URL  = $this->_tpl_vars['PREV_DAY_URL'];
 $NEXT_DAY_URL  = $this->_tpl_vars['NEXT_DAY_URL'];

 $Date =  postcalendar_getDate();
 if (!isset($y)) $y = substr($Date, 0, 4);
 if (!isset($m)) $m = substr($Date, 4, 2);
 if (!isset($d)) $d = substr($Date, 6, 2);

 // echo "<!-- There are " . count($A_EVENTS) . " A_EVENTS days -->\n";


 //==================================
 //FACILITY FILTERING (CHEMED)
 $facilities = getUserFacilities($_SESSION['authId']); // from users_facility
 $provinfo = getMyProviderInfo($_SESSION['authUserID']);
 $providers = getMyProviders($_SESSION['authUserID']);
 $selectedproviders = getSelectedProviders($_SESSION['authUserID']);
 //EOS FACILITY FILTERING (CHEMED)
 //==================================
[-/php-]




<div id="topToolbarRight">  <!-- this wraps some of the top toolbar items -->
<div id="functions">
<!-- stuff form element here to avoid the margin padding it introduces into the page in some browsers -->
<form name='theform' id='theform' action='calendar/index.php?module=PostCalendar&func=view&tplview=default&pc_category=&pc_topic=' method='post' onsubmit='return top.restoreSession()'>
<input type="hidden" name="jumpdate" id="jumpdate" value="">
<input type="hidden" name="viewtype" id="viewtype" value="[-php-]echo $viewtype;[-/php-]">
[-php-]
if ( !acl_check('admin','adm_cnf') ){
    echo "   <a href='#' value='" .xl ("Add"). "' onclick='newEvt(1, 9, 00, $Date, 0, 0, 2, 1)'  class='css_button_calendar red'><span>".xl("Add")."</span></a>\n";
}
[-/php-]
</div>

<div id="dateNAV">
<a href='#' name='bnsubmit' value='[-php-]echo xl ("Today")[-/php-]' onClick='GoToToday(theform);'  class='css_button_calendar'>
	<span>[-php-] echo xl("Today")[-/php-]</span>
</a>
<a id='pmonth' class='css_button_calendar' onclick='timeNav("pmonth","[-php-]echo $PREV_MONTH_URL[-/php-]");' href='#' onclick='top.restoreSession()'>
	<span class="navbutton navBack"></span>
</a>
<a id='nmonth' class='css_button_calendar' onclick='timeNav("nmonth","[-php-]echo $NEXT_MONTH_URL[-/php-]");' href='#' onclick='top.restoreSession()'>
	<span class="navbutton navForward"></span>
</a>
&nbsp;
[-php-]
echo xl(date('F', strtotime($Date))) . " " . date('Y', strtotime($Date));
[-/php-]
</div>

<div id="viewPicker">
[-php-]
echo "   <a href='#' type='button' id='printview' title='" .xl ("Print View"). "' class='css_button_calendar'><span>".xl("Print")."</span></a>\n";
echo "   <a href='#' type='button' value='" .xl ("Refresh"). "' onclick='javascript:refreshme()' class='css_button_calendar'><span>".xl("Refresh")."</span></a>\n";
echo "   <a href='#' type='button' id='dayview' title='" .htmlspecialchars( xl('Day View'), ENT_QUOTES). "' class='css_button_calendar'><span>".htmlspecialchars( xl('Day'), ENT_QUOTES)."</span></a>\n";
echo "   <a href='#' type='button' id='weekview' title='" .htmlspecialchars( xl('Week View'), ENT_QUOTES). "' class='css_button_calendar'><span>".htmlspecialchars( xl('Week'), ENT_QUOTES)."</span></a>\n";
echo "   <a href='#' type='button' id='monthview' title='" .htmlspecialchars( xl('Month View'), ENT_QUOTES). "' class='css_button_calendar active'><span>".htmlspecialchars( xl('Month'), ENT_QUOTES)."</span></a>\n";
[-/php-]
</div>
</div> <!-- end topToolbarRight -->
<div id="bottom">
<div id="bottomLeft">
<div id="datePicker">
[-php-]
    // caldate depends on what the user has clicked
    $caldate = strtotime($Date);
    $cMonth = date("m", $caldate);
    $cYear = date("Y", $caldate);
    $cDay = date("d", $caldate);

    include_once($GLOBALS['webserver_root'].'/interface/main/calendar/modules/PostCalendar/pntemplates/default/views/monthSelector.php');
[-/php-]
    
<table border="0" cellpadding="0" cellspacing="0">
<tr>
[-php-]

// compute the previous month date
// stay on the same day if possible
$pDay = $cDay;
$pMonth = $cMonth - 1;
$pYear = $cYear;
if ($pMonth < 1) { $pMonth = 12; $pYear = $cYear - 1; }
while (! checkdate($pMonth, $pDay, $pYear)) { $pDay = $pDay - 1; }
$prevMonth = sprintf("%d%02d%02d",$pYear,$pMonth,$pDay);

// compute the next month
// stay on the same day if possible
$nDay = $cDay;
$nMonth = $cMonth + 1;
$nYear = $cYear;
if ($nMonth > 12) { $nMonth = 1; $nYear = $cYear + 1; }
while (! checkdate($nMonth, $nDay, $nYear)) { $nDay = $nDay - 1; }
$nextMonth = sprintf("%d%02d%02d",$nYear,$nMonth,$nDay);
[-/php-]
<td class="tdDOW-small tdDatePicker tdNav" id="[-php-]echo $prevMonth[-/php-]" title="[-php-]echo xl(date("F", strtotime($prevMonth)));[-/php-]">&lt;</td>
<td colspan="5" class="tdMonthName-small">
[-php-]
echo xl(date('F', $caldate));
[-/php-]
</td>
<td class="tdDOW-small tdDatePicker tdNav" id="[-php-]echo $nextMonth[-/php-]" title="[-php-]echo xl(date("F", strtotime($nextMonth)));[-/php-]">&gt;</td>
<tr>
[-php-]
foreach ($DOWlist as $dow) {
    echo "<td class='tdDOW-small'>".$this->_tpl_vars['A_SHORT_DAY_NAMES'][$dow]."</td>";
}
[-/php-]
</tr>
[-php-]
$atmp = array_keys($A_EVENTS);

foreach ($atmp as $currdate) {
    $currdate = strtotime($currdate);
    if (date('w', $currdate) == $DOWlist[0]) {
        // start of week row
        $tr = "<tr>";
        echo $tr;
    }

    // set the TD class
    $tdClass = "tdMonthDay-small";
    if (date('m', $currdate) != $month) {
        $tdClass = "tdOtherMonthDay-small";
    }
    if ((date('w', $currdate) == 0) || (date('w', $currdate) == 6)) {
        $tdClass = "tdWeekend-small";
    }

    if (date('Ymd',$currdate) == $Date) {
        // $Date is defined near the top of this file
        // and is equal to whatever date the user has clicked
        $tdClass .= " currentDate";
    }

    // add a class so that jQuery can grab these days for the 'click' event
    $tdClass .= " tdDatePicker";

    // output the TD
    $td = "<td ";
    $td .= "class=\"".$tdClass."\" ";
    //$td .= "id=\"".date("Ymd", $currdate)."\" ";
    $td .= "id=\"".date("Ymd", $currdate)."\" ";
    $td .= "title=\"" . xl('Go to') . " ".date('F', $currdate)."\" ";
    $td .= "> ".date('d', $currdate)."</td>\n";
    echo $td;
   
    // end of week row
    if (date('w', $currdate) == $DOWlist[6]) echo "</tr>\n";
}
[-/php-]
</table>
</div>
<div id="bigCalHeader">
</div>

<div id="providerPicker" style="overflow-x:scroll;">
[-php-] xl('Providers','e'); [-/php-]
<div>
[-php-]
// ==============================
// FACILITY FILTERING (lemonsoftware)
// $facilities = getFacilities();
if ($_SESSION['authorizeduser'] == 1) {
  $facilities = getFacilities();
} else {
  $facilities = getUserFacilities($_SESSION['authId']); // from users_facility
  if (count($facilities) == 1)
    $_SESSION['pc_facility'] = key($facilities);
}
if (count($facilities) > 1) {
    echo "   <select name='pc_facility' id='pc_facility'  class='view1' >\n";
    if ( !$_SESSION['pc_facility'] ) $selected = "selected='selected'";
    // echo "    <option value='0' $selected>"  .xl('All Facilities'). "</option>\n";
    if (!$GLOBALS['restrict_user_facility']) echo "    <option value='0' $selected>" . xl('All Facilities') . "</option>\n";

    foreach ($facilities as $fa) {
        $selected = ( $_SESSION['pc_facility'] == $fa['id']) ? "selected='selected'" : "" ;
        echo "    <option style=background-color:".htmlspecialchars($fa['color'],ENT_QUOTES)." value='" .htmlspecialchars($fa['id'],ENT_QUOTES). "' $selected>"  .htmlspecialchars($fa['name'],ENT_QUOTES). "</option>\n";
    }
    echo "   </select>\n";
}
// EOS FF
// ==============================

 echo "</div>";
 
 echo "   <select multiple size='5' name='pc_usernamelist[]' id='pc_usernamelist' class='view2'>\n";
 echo "    <option value='__PC_ALL__'>"  .xl ("All Users"). "</option>\n";
 foreach ($provinfo as $doc) {
  $username = $doc['id'];
  echo "    <option value='$username'";
    foreach ($_REQUEST['pc_username'] as $provider)
   if ($provider == $username) echo " selected";
   
  echo ">" . htmlspecialchars($doc['lname'],ENT_QUOTES) . ", " . htmlspecialchars($doc['fname'],ENT_QUOTES) . "</option>\n";
 }
 echo "   </select>\n";

[-/php-]
</div>
[-php-]
if($_SESSION['pc_facility'] == 0){
[-/php-]
<div id="facilityColor">
 <table>
[-php-]
foreach ($facilities as $f){
echo "   <tr><td><div class='view1' style=background-color:".$f['color'].";font-weight:bold>".htmlspecialchars($f['name'],ENT_QUOTES)."</div></td></tr>";
}
[-/php-]
 </table>
</div>
[-php-]
}
[-/php-]
</form>

[-assign var="dayname" value=$DATE|date_format:"%w"-]
[-assign var="day"     value=$DATE|date_format:"%d"|string_format:"%1d"-]
[-assign var="month"   value=$DATE|date_format:"%m"|string_format:"%1d"-]
[-assign var="year"    value=$DATE|date_format:"%Y"|string_format:"%4d"-]
</div> <!-- end bottomLeft -->

<div id="bigCal">
[-php-]
/* used in debugging
foreach ($A_EVENTS as $date => $events) {
    echo $date." = ";
    foreach ($events as $oneE) {
        print_r($oneE);
        echo "<br><br>";
    }
    echo "<hr width=100%>";
}
*/
    

// This loops once for each provider to be displayed.
//
    
    foreach ($providers as $provider) {
    $providerid = $provider['id'];
        if( in_array( $providerid, $selectedproviders)){
                
                echo "<table>\n";
                echo " <tr>\n";
                echo "  <td colspan='7' class='providerheader'>";
                echo htmlspecialchars($provider['fname'],ENT_QUOTES)." ".htmlspecialchars($provider['lname'],ENT_QUOTES);
                echo "</td>\n";
                echo " </tr>\n";

                // output date headers
                echo " <tr>\n";
                $defaultDate = ""; // used when creating link for a 'new' event
                $in_cat_id = 0; // used when creating link for a 'new' event
                $dowCount = 0;
                foreach ($A_EVENTS as $date => $events) {
                    if ($defaultDate == "") $defaultDate = date("Ymd", strtotime($date));
                    echo "<td align='center' class='month_dateheader'>";
                    echo xl(date("D", strtotime($date)));
                    echo "</td>";
                    if ($dowCount++ == 6) { break; }
                }
                echo " </tr>\n";

                // For each day...
                // output a TD with an inner containing DIV positioned 'relative'

                foreach ($A_EVENTS as $date => $events) {
                
                    $eventdate = substr($date, 0, 4) . substr($date, 5, 2) . substr($date, 8, 2);

                    $gotoURL = pnModURL(__POSTCALENDAR__,'user','view',
                                    array('tplview'=>$template_view,
                                    'viewtype'=>'day',
                                    'Date'=> date("Ymd", strtotime($date)),
                                    'pc_username'=>$_SESSION['pc_username'],
                                    'pc_category'=>$category,
                                    'pc_topic'=>$topic));

                    if (date("w", strtotime($date)) == $DOWlist[0]) { echo "<tr>"; }
                    echo "<td class='schedule'>";

                    echo "<div class='calendar_day'>\n";

                    echo "<div class='month_daylink'>";
                    $dat = date("Ymd", strtotime($date));
                    //echo "<a href='".$gotoURL."' alt='Go to ".date("d M Y",strtotime($date))."' title='" . xl('Go to') . " " .date("d M Y", strtotime($date))."'>";
                    echo "<a onclick='ChangeViewDay(\"$dat\");' alt='Go to ".date("d M Y",strtotime($date))."' title='" . xl('Go to') . " " .date("d M Y", strtotime($date))."'>";
                    echo date("d", strtotime($date))."</a></div>";

                    if (count($events) == 0) { echo "&nbsp;"; }
            //=======================================================================================
            //=======================================================================================
                    foreach ($events as $event) {
                        
                        // skip events for other providers
                        // yeah, we've got that sort of overhead here... it ain't perfect
						//echo "<pre>";
						//print_r($event);
						//echo "</pre>";
                        if ($providerid != $event['aid']) { continue; }

                        // Omit IN and OUT events to reduce clutter in this month view
                        if (($event['catid'] == 2) || ($event['catid'] == 3)) { continue; }

                        // specially handle all-day events
                        if ($event['alldayevent'] == 1) {
                            $tmpTime = $times[0];
                            if (strlen($tmpTime['hour']) < 2) { $tmpTime['hour'] = "0".$tmpTime['hour']; }
                            if (strlen($tmpTime['minute']) < 2) { $tmpTime['minute'] = "0".$tmpTime['minute']; }
                            $event['startTime'] = $tmpTime['hour'].":".$tmpTime['minute'].":00";
                            $event['duration'] = ($calEndMin - $calStartMin) * 60;  // measured in seconds
                        }
						
                        // figure the start time and minutes (from midnight)
                        $starth = substr($event['startTime'], 0, 2);
                        $startm = substr($event['startTime'], 3, 2);
                        $eStartMin = $starth * 60 + $startm;
                        $startDateTime = strtotime($date." ".$event['startTime']);

                        // determine the class for the event DIV based on the event category
                        $evtClass = "event_appointment";
                        switch ($event['catid']) {
                            case 1:  // NO-SHOW appt
                                $evtClass = "event_noshow";
                                break;
                            case 2:  // IN office
                                $evtClass = "event_in";
                                break;
                            case 3:  // OUT of office
                                $evtClass = "event_out";
                                break;
                            case 4:  // VACATION
                            case 8:  // LUNCH
                            case 11: // RESERVED
                                $evtClass = "event_reserved";
                                break;
                            default: // some appointment
                                $evtClass = "event_appointment";
                                break;
                        }

                        // now, output the event DIV
                        
                        $eventid = $event['eid'];
                        $eventtype = sqlQuery("SELECT pc_cattype FROM openemr_postcalendar_categories as oc LEFT OUTER JOIN openemr_postcalendar_events as oe ON oe.pc_catid=oc.pc_catid WHERE oe.pc_eid='".$eventid."'");
                        $pccattype = '';
                        if($eventtype['pc_cattype']==1)
                        $pccattype = 'true';
                        $patientid = $event['pid'];
                        $query = " SELECT * FROM patient_data WHERE pid = 1638";
                        $res = sqlStatement($query);
                        $row = sqlFetchArray($res);
                        if($_SESSION['authUserID']==1){
                            //echo " ".$patientid;
                           // echo "<pre>";
                            //print_r($row);
                            //echo "</pre>";
                        }
                        
                        
                        $commapos = strpos($event['patient_name'], ",");
                        $lname = substr($event['patient_name'], 0, $commapos);
                        $fname = substr($event['patient_name'], $commapos + 2);
                        $patient_dob = $event['patient_dob'];
                        $patient_age = $event['patient_age'];
                        $catid = $event['catid'];
                        $comment = addslashes($event['hometext']);
                        $catname = $event['catname'];
                        $title = "Age $patient_age ($patient_dob)";

                        // format the time specially
                        $displayTime = date("g", $startDateTime);
                        if (date("i", $startDateTime) == "00") {
                            $displayTime .= (date("a", $startDateTime));
                        }
                        else {
                            $displayTime .= (date(":ia", $startDateTime));
                        }

                        if ($comment && $GLOBALS['calendar_appt_style'] < 4) $title .= " " . $comment;

                        // the divTitle is what appears when the user hovers the mouse over the DIV
                            $divTitle = dateformat (strtotime($date),true);
                        $result = sqlStatement("SELECT name,id,color FROM facility WHERE id=(SELECT pc_facility FROM openemr_postcalendar_events WHERE pc_eid=".$eventid.")");
                        $row = sqlFetchArray($result);
                        $color=$event["catcolor"];
                        if($GLOBALS['event_color']==2)
                        $color=$row['color'];
                        $divTitle .= "\n" .htmlspecialchars($row['name'],ENT_QUOTES);
                        $content = "";
                        if ($catid == 4 || $catid == 8 || $catid == 11) {
                            if ($catid ==  4) $catname = xl("VACATION");
                            else if ($catid ==  8) $catname = xl("LUNCH");
                            else if ($catid == 11) $catname = xl("RESERVED");

                            $atitle = $catname;
                            if ($comment) $atitle .= " $comment";
                            $divTitle .= "\n[".$atitle ."]";
                            $content .= $displayTime;
                            $content .= "&nbsp;".$catname;
                        }
                        else {
                            // some sort of patient appointment
                            $divTitle .= "\r\n[".$catname.' '.htmlspecialchars($comment, ENT_QUOTES) ."]".htmlspecialchars($fname,ENT_QUOTES)." ".htmlspecialchars($lname,ENT_QUOTES);
                            $content .= $displayTime;
                            if ($patientid) {
                                // include patient name and link to their details
                                $link_title = htmlspecialchars($fname,ENT_QUOTES)." ".htmlspecialchars($lname,ENT_QUOTES). " \n";
                                $link_title .= xl('Age') . ": ".$patient_age."\n" . xl('DOB') . ": ".$patient_dob.htmlspecialchars($comment, ENT_QUOTES)."\n";
                                $link_title .= "(" . xl('Click to view') . ")";
                                $content .= "<a href='javascript:goPid($patientid)' title='$link_title'>";
                                $content .= "<img src='$TPL_IMAGE_PATH/user-green.gif' border='0' title='$link_title' alt='View Patient' />";
                                if ($catid == 1) $content .= "<strike>";
                                $content .= htmlspecialchars($lname);
                                if ($GLOBALS['calendar_appt_style'] != 1) {
                                    $content .= "," . htmlspecialchars($fname);
                                    if ($event['title'] && $GLOBALS['calendar_appt_style'] >= 3) {
                                        $content .= "(" . $event['title'];
                                        if ($event['hometext'] && $GLOBALS['calendar_appt_style'] >= 4)
                                        $content .= ": <font color='green'>" . htmlspecialchars(trim($event['hometext'])) . "</font>";
                                        $content .= ")";
                                    }
                                }
                                if ($catid == 1) $content .= "</strike>";
                                $content .= "</a>";
                            }
                            else {
                                // no patient id, just output the category name
                                $content .= " ".$catname;
                            }
                        }
                        $divTitle .= "\n(" . xl('double click to edit') . ")";
                        if($_SESSION['pc_facility'] == 0){
                                echo "<div class='".$evtClass." month_event' style='background-color:".$color.
                                        "' title='".$divTitle."'".
                                        " id='".$eventdate."-".$eventid."-".$pccattype."'".
                                        ">";
                                echo $content;
                                echo "</div>\n";
                        }
                        elseif($_SESSION['pc_facility'] == $row['id']){
                                echo "<div class='".$evtClass." month_event' style='background-color:".$event["catcolor"].
                                    "' title='".$divTitle."'".
                                    " id='".$eventdate."-".$eventid."-".$pccattype."'".
                                    ">";
                                echo $content;
                                echo "</div>\n";
                        }
                        else{
                                echo "<div class='".$evtClass." month_event' style='background-color:#DDDDDD".
                                    "' title='".$divTitle."'".
                                    " id='".$eventdate."-".$eventid."-".$pccattype."'".
                                    ">";
                                echo "<span style='color:red;text-align:center;'>".$displayTime." ".htmlspecialchars($row['name'],ENT_QUOTES)."</span>";
                                echo "</div>\n";
                        }
                    } // end EVENT loop
            //=======================================================================================
            //=======================================================================================
                    echo "</div>";
                    echo "</td>";
                    if (date("w", strtotime($date)) == $DOWlist[6]) { echo "</tr>"; }
                } // end date

                echo "</table>\n";
                echo "<P>"; 
        }
    /*}else{
      
                echo "<table>\n";
                echo " <tr>\n";
                echo "  <td colspan='7' class='providerheader'>";
                echo htmlspecialchars($provider['fname'],ENT_QUOTES)." ".htmlspecialchars($provider['lname'],ENT_QUOTES);
                echo "</td>\n";
                echo " </tr>\n";

                // output date headers
                echo " <tr>\n";
                $defaultDate = ""; // used when creating link for a 'new' event
                $in_cat_id = 0; // used when creating link for a 'new' event
                $dowCount = 0;
                foreach ($A_EVENTS as $date => $events) {
                    if ($defaultDate == "") $defaultDate = date("Ymd", strtotime($date));
                    echo "<td align='center' class='month_dateheader'>";
                    echo xl(date("D", strtotime($date)));
                    echo "</td>";
                    if ($dowCount++ == 6) { break; }
                }
                echo " </tr>\n";

                // For each day...
                // output a TD with an inner containing DIV positioned 'relative'

                foreach ($A_EVENTS as $date => $events) {
                    $eventdate = substr($date, 0, 4) . substr($date, 5, 2) . substr($date, 8, 2);

                    $gotoURL = pnModURL(__POSTCALENDAR__,'user','view',
                                    array('tplview'=>$template_view,
                                    'viewtype'=>'day',
                                    'Date'=> date("Ymd", strtotime($date)),
                                    'pc_username'=>$pc_username,
                                    'pc_category'=>$category,
                                    'pc_topic'=>$topic));

                    if (date("w", strtotime($date)) == $DOWlist[0]) { echo "<tr>"; }
                    echo "<td class='schedule'>";

                    echo "<div class='calendar_day'>\n";

                    echo "<div class='month_daylink'>";
                    echo "<a href='".$gotoURL."' alt='Go to ".date("d M Y",strtotime($date))."' title='" . xl('Go to') . " " .date("d M Y", strtotime($date))."'>";
                    echo date("d", strtotime($date))."</a></div>";

                    if (count($events) == 0) { echo "&nbsp;"; }
            //=======================================================================================
            //=======================================================================================
                    foreach ($events as $event) {
                        // skip events for other providers
                        // yeah, we've got that sort of overhead here... it ain't perfect
                        if ($providerid != $event['aid']) { continue; }

                        // Omit IN and OUT events to reduce clutter in this month view
                        if (($event['catid'] == 2) || ($event['catid'] == 3)) { continue; }

                        // specially handle all-day events
                        if ($event['alldayevent'] == 1) {
                            $tmpTime = $times[0];
                            if (strlen($tmpTime['hour']) < 2) { $tmpTime['hour'] = "0".$tmpTime['hour']; }
                            if (strlen($tmpTime['minute']) < 2) { $tmpTime['minute'] = "0".$tmpTime['minute']; }
                            $event['startTime'] = $tmpTime['hour'].":".$tmpTime['minute'].":00";
                            $event['duration'] = ($calEndMin - $calStartMin) * 60;  // measured in seconds
                        }

                        // figure the start time and minutes (from midnight)
                        $starth = substr($event['startTime'], 0, 2);
                        $startm = substr($event['startTime'], 3, 2);
                        $eStartMin = $starth * 60 + $startm;
                        $startDateTime = strtotime($date." ".$event['startTime']);

                        // determine the class for the event DIV based on the event category
                        $evtClass = "event_appointment";
                        switch ($event['catid']) {
                            case 1:  // NO-SHOW appt
                                $evtClass = "event_noshow";
                                break;
                            case 2:  // IN office
                                $evtClass = "event_in";
                                break;
                            case 3:  // OUT of office
                                $evtClass = "event_out";
                                break;
                            case 4:  // VACATION
                            case 8:  // LUNCH
                            case 11: // RESERVED
                                $evtClass = "event_reserved";
                                break;
                            default: // some appointment
                                $evtClass = "event_appointment";
                                break;
                        }

                        // now, output the event DIV
                        if($_SESSION['authUserID']==1){
                            echo "Roy Jimenez1";
                        }
                        $eventid = $event['eid'];
                        $eventtype = sqlQuery("SELECT pc_cattype FROM openemr_postcalendar_categories as oc LEFT OUTER JOIN openemr_postcalendar_events as oe ON oe.pc_catid=oc.pc_catid WHERE oe.pc_eid='".$eventid."'");
                        $pccattype = '';
                        if($eventtype['pc_cattype']==1)
                        $pccattype = 'true';
                        $patientid = $event['pid'];
                        $commapos = strpos($event['patient_name'], ",");
                        $lname = substr($event['patient_name'], 0, $commapos);
                        $fname = substr($event['patient_name'], $commapos + 2);
                        $patient_dob = $event['patient_dob'];
                        $patient_age = $event['patient_age'];
                        $catid = $event['catid'];
                        $comment = addslashes($event['hometext']);
                        $catname = $event['catname'];
                        $title = "Age $patient_age ($patient_dob)";

                        // format the time specially
                        $displayTime = date("g", $startDateTime);
                        if (date("i", $startDateTime) == "00") {
                            $displayTime .= (date("a", $startDateTime));
                        }
                        else {
                            $displayTime .= (date(":ia", $startDateTime));
                        }

                        if ($comment && $GLOBALS['calendar_appt_style'] < 4) $title .= " " . $comment;

                        // the divTitle is what appears when the user hovers the mouse over the DIV
                            $divTitle = dateformat (strtotime($date),true);
                        $result = sqlStatement("SELECT name,id,color FROM facility WHERE id=(SELECT pc_facility FROM openemr_postcalendar_events WHERE pc_eid=".$eventid.")");
                        $row = sqlFetchArray($result);
                        $color=$event["catcolor"];
                        if($GLOBALS['event_color']==2)
                        $color=$row['color'];
                        $divTitle .= "\n" .htmlspecialchars($row['name'],ENT_QUOTES);
                        $content = "";
                        if ($catid == 4 || $catid == 8 || $catid == 11) {
                            if ($catid ==  4) $catname = xl("VACATION");
                            else if ($catid ==  8) $catname = xl("LUNCH");
                            else if ($catid == 11) $catname = xl("RESERVED");

                            $atitle = $catname;
                            if ($comment) $atitle .= " $comment";
                            $divTitle .= "\n[".$atitle ."]";
                            $content .= $displayTime;
                            $content .= "&nbsp;".$catname;
                        }
                        else {
                            // some sort of patient appointment
                            $divTitle .= "\r\n[".$catname.' '.htmlspecialchars($comment, ENT_QUOTES) ."]".htmlspecialchars($fname,ENT_QUOTES)." ".htmlspecialchars($lname,ENT_QUOTES);
                            $content .= $displayTime;
                            if ($patientid) {
                                // include patient name and link to their details
                                $link_title = htmlspecialchars($fname,ENT_QUOTES)." ".htmlspecialchars($lname,ENT_QUOTES). " \n";
                                $link_title .= xl('Age') . ": ".$patient_age."\n" . xl('DOB') . ": ".$patient_dob.htmlspecialchars($comment, ENT_QUOTES)."\n";
                                $link_title .= "(" . xl('Click to view') . ")";
                                $content .= "<a href='javascript:goPid($patientid)' title='$link_title'>";
                                $content .= "<img src='$TPL_IMAGE_PATH/user-green.gif' border='0' title='$link_title' alt='View Patient' />";
                                if ($catid == 1) $content .= "<strike>";
                                $content .= htmlspecialchars($lname);
                                if ($GLOBALS['calendar_appt_style'] != 1) {
                                    $content .= "," . htmlspecialchars($fname);
                                    if ($event['title'] && $GLOBALS['calendar_appt_style'] >= 3) {
                                        $content .= "(" . $event['title'];
                                        if ($event['hometext'] && $GLOBALS['calendar_appt_style'] >= 4)
                                        $content .= ": <font color='green'>" . htmlspecialchars(trim($event['hometext'])) . "</font>";
                                        $content .= ")";
                                    }
                                }
                                if ($catid == 1) $content .= "</strike>";
                                $content .= "</a>";
                            }
                            else {
                                // no patient id, just output the category name
                                $content .= " ".$catname;
                            }
                        }
                        $divTitle .= "\n(" . xl('double click to edit') . ")";
                        if($_SESSION['pc_facility'] == 0){
                                echo "<div class='".$evtClass." month_event' style='background-color:".$color.
                                        "' title='".$divTitle."'".
                                        " id='".$eventdate."-".$eventid."-".$pccattype."'".
                                        ">";
                                echo $content;
                                echo "</div>\n";
                        }
                        elseif($_SESSION['pc_facility'] == $row['id']){
                                echo "<div class='".$evtClass." month_event' style='background-color:".$event["catcolor"].
                                    "' title='".$divTitle."'".
                                    " id='".$eventdate."-".$eventid."-".$pccattype."'".
                                    ">";
                                echo $content;
                                echo "</div>\n";
                        }
                        else{
                                echo "<div class='".$evtClass." month_event' style='background-color:#DDDDDD".
                                    "' title='".$divTitle."'".
                                    " id='".$eventdate."-".$eventid."-".$pccattype."'".
                                    ">";
                                echo "<span style='color:red;text-align:center;'>".$displayTime." ".htmlspecialchars($row['name'],ENT_QUOTES)."</span>";
                                echo "</div>\n";
                        }
                    } // end EVENT loop
            //=======================================================================================
            //=======================================================================================
                    echo "</div>";
                    echo "</td>";
                    if (date("w", strtotime($date)) == $DOWlist[6]) { echo "</tr>"; }
                } // end date

                echo "</table>\n";
                echo "<P>";
    }*/
        
            
    } // end provider


 // [-*footer*-]
 // [-include file="$TPL_NAME/views/global/footer.html"-]
 // [-include file="$TPL_NAME/views/footer.html"-]

[-/php-]
</div>  <!-- end bigCal DIV -->
</div> <!-- end bottom DIV -->
</body>

<script language='JavaScript'>

    $(document).ready(function(){
        $("#pc_usernamelist").change(function() { ChangeProviders(this); });
        $("#pc_facility").change(function() { ChangeProviders(this); });
        $("#dayview").click(function() { ChangeView(this); });
        $("#weekview").click(function() { ChangeView(this); });
        //$("#monthview").click(function() { ChangeView(this); });
        //$("#yearview").click(function() { ChangeView(this); });
        $(".tdDatePicker").click(function() { ChangeDate(this); });
        $("#datePicker .tdNav").mouseover(function() { $(this).toggleClass("tdDatePickerHighlight"); });
        $("#datePicker .tdNav").mouseout(function() { $(this).toggleClass("tdDatePickerHighlight"); });
        $("#printview").click(function() { PrintView(this); });
        $(".month_event").dblclick(function() { EditEvent(this); });
        $(".month_event").mouseover(function() { $(this).toggleClass("event_highlight"); });
        $(".month_event").mouseout(function() { $(this).toggleClass("event_highlight"); });

        $(".tdMonthName-small").click(function() {
            
            dpCal=$("#datePicker>table"); 
            mp = $("#monthPicker"); mp.width(dpCal.width()); mp.toggle();});

    });
    
    /* pop up a window to print the current view
     */
    var PrintView = function (eventObject) {
        printURL = "[-php-]echo pnModURL(__POSTCALENDAR__,'user','view',
                        array('tplview'=>$template_view,
                        'viewtype'=>$viewtype,
                        'Date'=> $Date,
                        'print'=> 1,
                        'pc_username'=>$pc_username,
                        'pc_category'=>$category,
                        'pc_topic'=>$topic));[-/php-]";
        window.open(printURL,'printwindow','width=740,height=480,toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,copyhistory=no,resizable=yes');
        return false;
    }

    /* change the current date based upon what the user clicked in 
     * the datepicker DIV
     */
    var ChangeDate = function(eObj) {
        /*baseURL = "[-php-]echo pnModURL(__POSTCALENDAR__,'user','view',
                        array('tplview'=>$template_view,
                        'viewtype'=>$viewtype,
                        'Date'=> '~REPLACEME~',
                        'pc_username'=>$pc_username,
                        'pc_category'=>$category,
                        'pc_topic'=>$topic));[-/php-]";
        newURL = baseURL.replace(/~REPLACEME~/, eObj.id);
        //document.location.href=newURL;
        
		$.ajax({
		  type: "POST",
		  cache: false,
		  url: newURL, // preview.php
		  data: '', // all form fields
		  success: function (data) {
			$("#info").html(data);
		  } // success
		}); // ajax*/
        
        $extradata = "";
            
            if( $('#pc_usernamelist :selected').length > 0){
                //build an array of selected values
                var selectednumbers = [];
                $('#pc_usernamelist :selected').each(function(i, selected) {
                    selectednumbers[i] = $(selected).val();
                    $data = "&pc_username[]="+selectednumbers[i];
                    $extradata +=$data;
                });
                //post data to handler script. note the JSON.stringify call
                
            }
            
            $extradata += "&Date="+eObj.id;
            
		$.ajax({
		  type: "POST",
		  cache: false,
		  url: $("#theform").attr('action'), // preview.php
		  data: $("#theform").serialize() + $extradata, // all form fields
		  success: function (data) {
			$("#info").html(data);
		  } // success
		}); // ajax
    }

</script>


</html>
